package com.zkh.myutils.io.excel.opcpack;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.zkh.myutils.io.excel.XMLParseException;
import com.zkh.myutils.io.excel.XMLParseUtils;

/**
 * 共享字符串XML生成
 * @author zkh
 */
public class SharedStringsXML {
	//共享字符串集合
	private List<String> sharedStringList;
	//字符串长度
	private int total;
	
	/**
	 * 构造方法
	 * @param sharedStringList 共享字符串集合
	 * @param total 字符串长度
	 */
	public SharedStringsXML(List<String> sharedStringList, int total) {
		this.sharedStringList = sharedStringList;
		this.total = total;
	}
	
	/**
	 * 获取格式化XML流并写入
	 * @param outputStream 输出流
	 * @throws IOException
	 */
	public void writeFormatStream(OutputStream outputStream) throws IOException {
		try {
			//文档构建器
			DocumentBuilder builder = XMLParseUtils.createDocumentBuilder();
			//创建文档对象
			Document doc = builder.newDocument();
			doc.setXmlStandalone(true);
			//创建根节点
			Element root = doc.createElement("sst");
			//属性
			root.setAttribute("xmlns", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
			root.setAttribute("count", Integer.toString(total));
			root.setAttribute("uniqueCount", Integer.toString(sharedStringList.size()));
			//根节点挂在文档上
			doc.appendChild(root);
			//遍历数据
			for(String ss: sharedStringList) {
				//创建si节点
				Element siNode = doc.createElement("si");
				//创建t节点
				Element tNode = doc.createElement("t");
				//保存数据
				tNode.setTextContent(ss);
				//保存节点
				siNode.appendChild(tNode);
				root.appendChild(siNode);
			}
			//生成流转换器
			Transformer transformer = XMLParseUtils.createTransformer();
			//开始转换
			transformer.transform(new DOMSource(doc), new StreamResult(outputStream));
			//刷新
			outputStream.flush();
		} catch (ParserConfigurationException | TransformerException e) {
			throw new XMLParseException(e);
		}
	}
}
